require(['./config'], () => {
    require(['template', 'header', 'footer', 'magnifier', 'fly'], (template, header) => {
        class Detail {
            constructor() {
                this.getData().then(() => {

                    this.addCar();
                    this.addCount();
                    this.delCount();
                    this.glass();
                    this.youLike().then(() => {
                        this.gotoDetail();
                    });
                });

            }

            //获取页面数据
            getData() {
                const id = location.search.slice(4);
                return new Promise(resolve => {
                    $.get(`http://www.xiongmaoyouxuan.com/api/detail?id=${id}`, resp => {
                        if (resp.code === 200) {
                            const {
                                id,
                                photo,
                                favoritedCount,
                                title,
                                qunTitle,
                                price,
                                accessoryHints,
                                originPrice,
                                descContentList,
                                couponValue,
                                saleNum
                            }
                                = resp.data.detail;
                            this.detail = {
                                id,
                                photo: photo.slice(0, 4),
                                favoritedCount,
                                title,
                                qunTitle,
                                price,
                                accessoryHints,
                                originPrice,
                                descContentList,
                                couponValue,
                                saleNum
                            };
                            $('#goods_detail').html(template('detailTemplate', {
                                ...this.detail,
                                city: ['成都', '北京', '武汉',]
                            }));
                            $('#bigImg').html(template('bigImgTemplate', {...this.detail}));
                            resolve();

                        }

                    })
                })
            }

            //猜你喜欢
            youLike() {
                const pid = location.hash.slice(5);
                return new Promise(resolve => {
                    $.get(`http://www.xiongmaoyouxuan.com/api/tab/${pid}?start=0`, resp => {
                        if (resp.code === 200) {
                            let {list} = resp.data.items;
                            list = list.slice(0, 6)
                            $('#youLike-ul').html(template('youLikeTemplate', {list}));
                        }
                    });
                    resolve();
                })

            }

            //猜你喜欢跳转
            gotoDetail() {
                const pid = location.hash.slice(5);
                $('#youLike-ul').on('click', 'li', function () {
                    const id = $(this).attr('data-pid');
                    let tempwindow = window.open('_blank');
                    tempwindow.location = `/html/detail.html?id=${id}#pid=${pid}`;
                })
            }


            //放大镜
            glass() {
                let magnifierConfig = {
                    magnifier: "#magnifier1",//最外层的大容器
                    width: 500,//承载容器宽
                    height: 500,//承载容器高
                    moveWidth: null,//如果设置了移动盒子的宽度，则不计算缩放比例
                    zoom: 5//缩放比例
                };

                let _magnifier = magnifier(magnifierConfig);
            }

            //添加按钮
            addCount() {
                $('#addToCar').on('click', () => {
                    let count = $('#checkCount').val() - 0 + 1;
                    $('#checkCount').val(count);
                })
            }

            //减少按钮
            delCount() {
                $('#delToCar').on('click', () => {
                    let count = $('#checkCount').val() - 1;
                    if (count <= 1) count = 1
                    $('#checkCount').val(count);
                })
            }


            //加入购物车
            addCar() {
                $('#addCar-btn').on('click', e => {
                    this.fly(e)
                    let car = localStorage.getItem('car');
                    let count = $('#checkCount').val() - 0;
                    if (car) {
                        car = JSON.parse(car);
                        //判断是否存入了购物车

                        const isExist = car.some(shop => {
                            return shop.id === this.detail.id;
                        });
                        //已存入购物车，添加数量
                        if (isExist) {
                            car = car.map(shop => {
                                if (shop.id === this.detail.id) {
                                    shop.count += count;
                                }
                                return shop;
                            })
                        } else {
                            car.push({...this.detail, count: count, check: true});
                        }
                        localStorage.setItem('car', JSON.stringify(car));
                    } else {
                        localStorage.setItem('car', JSON.stringify([{...this.detail, count: count, check: true}]));
                    }
                });

            }

            //飞入购物车
            fly(e) {
                $(`<img class="fly" src="${this.detail.photo[0].url}">`).fly({

                    start: {
                        left: e.clientX,  //开始位置（必填）#fly元素会被设置成position: fixed
                        top: e.clientY,  //开始位置（必填）
                    },
                    end: {
                        left: $('#car-count').offset().left - $(window).scrollLeft(), //结束位置（必填）
                        top: $('#car-count').offset().top - $(window).scrollTop()  //结束位置（必填）
                        // width: 100, //结束时高度
                        // height: 100, //结束时高度
                    },
                    // autoPlay: false, //是否直接运动,默认true
                    speed: 0.7, //越大越快，默认1.2
                    // vertex_Rtop: 100, //运动轨迹最高点top值，默认20
                    onEnd: function () {
                        this.destroy()
                        // 重新计算购物车总数量
                        // 接收header对象调用header的方法实现计算
                        header.getCarCount();
                    } //结束回调
                })
            }
        }

        new Detail();
    })
})



